package cn.fancylab.template.web.action.manager.devcie;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.jivesoftware.smack.packet.Message;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eboo.openfire.cmd.sub.CabinetBoxCailOrigin;
import com.eboo.openfire.cmd.sub.CabinetBoxCailWeight;
import com.eboo.openfire.cmd.sub.CabinetBoxGetCnt;
import com.eboo.openfire.cmd.sub.CabinetBoxGetWeight;
import com.eboo.openfire.cmd.sub.CabinetBoxSearch;
import com.eboo.openfire.cmd.sub.CabinetBoxSigObjWeight;
import com.eboo.openfire.cmd.sub.CabinetBoxSigObjWeightErr;

import cn.fancylab.model.acl.AuthUser;
import cn.fancylab.model.bs.DeviceCabinetBox;
import cn.fancylab.model.bs.DeviceController;
import cn.fancylab.model.bs.DeviceGateway;
import cn.fancylab.service.DaoService;
import cn.fancylab.template.untrans.OpenFireService;
import cn.fancylab.template.util.JsonUtil;
import cn.fancylab.template.vo.TableListVo;
import cn.fancylab.template.web.action.admin.BaseAdminController;
import cn.fancylab.untrans.impl.AbstractCacheService;
import cn.fancylab.web.component.acl.SecurityUtil;
import cn.fancylab.web.support.FancyVelocityView;
import cn.fancylab.web.support.JsonStrDirectOut;
import cn.fancylab.xmpp.magent.MessageListener;

@Controller
public class CabinetBoxController extends BaseAdminController implements InitializingBean {
	@Autowired
	@Qualifier("daoService")
	private DaoService daoService;

	@Autowired
	@Qualifier("openFireService")
	private OpenFireService openFireService;

	@Autowired
	@Qualifier("redisCacheService")
	private AbstractCacheService redisCacheService;

	@RequestMapping(value = "/manager/device/cabinetbox/list.xhtml")
	public String list(ModelMap model) {
		return "manager/device/cabinetbox/list.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/list_data.xhtml")
	public String list_data(ModelMap model) {
		HttpServletRequest request = getRequest();

		int pagesize = 10;
		int page = 0;
		String currentpage = request.getParameter("page");
		String limit = request.getParameter("limit");
		String alias_name = request.getParameter("alias_name");

		if (StringUtils.isNotBlank(currentpage)) {
			page = Integer.valueOf(currentpage) - 1;
		}
		if (StringUtils.isNotBlank(limit)) {
			pagesize = Integer.valueOf(limit);
		}
		DetachedCriteria query = DetachedCriteria.forClass(DeviceCabinetBox.class);
		query.add(Restrictions.eq("is_del", 0));
		if (StringUtils.isNotBlank(alias_name)) {
			query.add(Restrictions.like("alias_name", "%".concat(alias_name).concat("%")));
		}
		int count = daoService.getObjectCountByCriteria(query);
		query.setFetchMode("deviceGateway", FetchMode.JOIN);
		query.setProjection(null);
		List<DeviceCabinetBox> list = daoService.findByCriteria(query, page * pagesize, pagesize);

		TableListVo<DeviceCabinetBox> tableListVo = new TableListVo<DeviceCabinetBox>();
		tableListVo.setCode(0);
		tableListVo.setMsg("");
		tableListVo.setCount(count + "");
		tableListVo.setData(list);

		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(tableListVo)));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/add.xhtml")
	public String add(String uuid) {
		return "manager/device/cabinetbox/form.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/edit.xhtml")
	public String edit(String uuid, ModelMap model) {
		DeviceCabinetBox deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class, uuid);
		model.put("deviceCabinetBox", deviceCabinetBox);
		return "manager/device/cabinetbox/form.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/save.xhtml")
	public String save(DeviceCabinetBox deviceCabinetBoxParameter) {
		AuthUser loginUser = SecurityUtil.getLogonUser();

		DeviceCabinetBox deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class,
				deviceCabinetBoxParameter.getUuid());

		if (null == deviceCabinetBox) {
			deviceCabinetBox = new DeviceCabinetBox();
			deviceCabinetBox.setUuid(UUID.randomUUID().toString());
			deviceCabinetBox.setIs_del(0);
			deviceCabinetBox.setAdd_date(new Date());
			deviceCabinetBox.setAdd_user_id(loginUser.getId());
		} else {
			deviceCabinetBox.setUp_date(new Date());
			deviceCabinetBox.setUp_user_id(loginUser.getId());
		}
		deviceCabinetBox.getDeviceGateway().setUuid(deviceCabinetBoxParameter.getDeviceGateway().getUuid());
		deviceCabinetBox.setCabinetbox_name(deviceCabinetBoxParameter.getCabinetbox_name());
		deviceCabinetBox.setAlias_name(deviceCabinetBoxParameter.getAlias_name());
		deviceCabinetBox.setAddress_485(deviceCabinetBoxParameter.getAddress_485());
		deviceCabinetBox.setRun_state(deviceCabinetBoxParameter.getRun_state());
		deviceCabinetBox.setDz_value(deviceCabinetBoxParameter.getDz_value());
		deviceCabinetBox.setDz_value_err(deviceCabinetBoxParameter.getDz_value_err());
		deviceCabinetBox.setBd_value(deviceCabinetBoxParameter.getBd_value());
		deviceCabinetBox.setLc(deviceCabinetBoxParameter.getLc());

		daoService.saveObject(deviceCabinetBox);

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(deviceCabinetBox)));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/del.xhtml")
	public String del(String[] uuid) {
		AuthUser loginUser = SecurityUtil.getLogonUser();

		DeviceCabinetBox deviceCabinetBox;
		for (int i = 0, len = uuid.length; i < len; i++) {
			if (StringUtils.isNotBlank(uuid[i])) {
				deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class, uuid[i]);

				if (null != deviceCabinetBox) {
					deviceCabinetBox.setIs_del(1);
					deviceCabinetBox.setDel_date(new Date());
					deviceCabinetBox.setDel_user_id(loginUser.getId());
					daoService.saveObject(deviceCabinetBox);
				}
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/CabinetBoxCailOrigin.xhtml")
	public String cabinetBoxCailOrigin(String uuid, Boolean state) {
		DeviceCabinetBox deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class, uuid);
		if (null != deviceCabinetBox && deviceCabinetBox.getDeviceGateway().getUuid() != null) {
			DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class,
					deviceCabinetBox.getDeviceGateway().getUuid());
			if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
				DeviceController deviceController = daoService.getObject(DeviceController.class,
						deviceGateway.getDeviceController().getUuid());
				if (null != deviceController && deviceController.getOpenfire_username() != null) {
					CabinetBoxCailOrigin cabinetBoxCailOrigin = new CabinetBoxCailOrigin();
					cabinetBoxCailOrigin.setBusinessType((byte) 0);
					cabinetBoxCailOrigin.setGatewayIdentifiedNo(deviceGateway.getIdentified_no());
					cabinetBoxCailOrigin.setAddr(Byte.valueOf(deviceCabinetBox.getAddress_485()));

					openFireService.sendMessage(deviceController.getOpenfire_username(),
							JsonUtil.serialize(cabinetBoxCailOrigin), UUID.randomUUID().toString(),
							new MessageListener() {
								@Override
								public String processAndGetReply(Message message) {
									System.out.println(message.getBody());
									return null;
								}
							});
				}
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/cabinetBoxCailWeight.xhtml")
	public String cabinetBoxCailWeight(String uuid, Boolean state) {
		DeviceCabinetBox deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class, uuid);
		if (null != deviceCabinetBox && deviceCabinetBox.getDeviceGateway().getUuid() != null) {
			DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class,
					deviceCabinetBox.getDeviceGateway().getUuid());
			if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
				DeviceController deviceController = daoService.getObject(DeviceController.class,
						deviceGateway.getDeviceController().getUuid());
				if (null != deviceController && deviceController.getOpenfire_username() != null) {
					CabinetBoxCailWeight cabinetBoxCailWeight = new CabinetBoxCailWeight();
					cabinetBoxCailWeight.setBusinessType((byte) 0);
					cabinetBoxCailWeight.setGatewayIdentifiedNo(deviceGateway.getIdentified_no());
					cabinetBoxCailWeight.setAddr(Byte.valueOf(deviceCabinetBox.getAddress_485()));
					cabinetBoxCailWeight.setWeight(deviceCabinetBox.getBd_value().getBytes());

					openFireService.sendMessage(deviceController.getOpenfire_username(),
							JsonUtil.serialize(cabinetBoxCailWeight), UUID.randomUUID().toString(),
							new MessageListener() {

								@Override
								public String processAndGetReply(Message message) {
									System.out.println(message.getBody());
									return null;
								}

							});
				}
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/cabinetBoxGetCnt.xhtml")
	public String cabinetBoxGetCnt(String uuid, Boolean state) {
		DeviceCabinetBox deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class, uuid);
		if (null != deviceCabinetBox && deviceCabinetBox.getDeviceGateway().getUuid() != null) {
			DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class,
					deviceCabinetBox.getDeviceGateway().getUuid());
			if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
				DeviceController deviceController = daoService.getObject(DeviceController.class,
						deviceGateway.getDeviceController().getUuid());
				if (null != deviceController && deviceController.getOpenfire_username() != null) {
					CabinetBoxGetCnt cabinetBoxGetCnt = new CabinetBoxGetCnt();
					cabinetBoxGetCnt.setBusinessType((byte) 0);
					cabinetBoxGetCnt.setGatewayIdentifiedNo(deviceGateway.getIdentified_no());
					cabinetBoxGetCnt.setAddr(Byte.valueOf(deviceCabinetBox.getAddress_485()));

					openFireService.sendMessage(deviceController.getOpenfire_username(),
							JsonUtil.serialize(cabinetBoxGetCnt), UUID.randomUUID().toString(), new MessageListener() {

								@Override
								public String processAndGetReply(Message message) {
									System.out.println(message.getBody());
									return null;
								}

							});
				}
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/cabinetBoxGetWeight.xhtml")
	public String cabinetBoxGetWeight(String uuid, Boolean state) {
		DeviceCabinetBox deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class, uuid);
		if (null != deviceCabinetBox && deviceCabinetBox.getDeviceGateway().getUuid() != null) {
			DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class,
					deviceCabinetBox.getDeviceGateway().getUuid());
			if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
				DeviceController deviceController = daoService.getObject(DeviceController.class,
						deviceGateway.getDeviceController().getUuid());
				if (null != deviceController && deviceController.getOpenfire_username() != null) {
					CabinetBoxGetWeight cabinetBoxGetWeight = new CabinetBoxGetWeight();
					cabinetBoxGetWeight.setBusinessType((byte) 0);
					cabinetBoxGetWeight.setControllerIdentifiedNo(deviceController.getIdentified_no());
					cabinetBoxGetWeight.setGatewayIdentifiedNo(deviceGateway.getIdentified_no());
					cabinetBoxGetWeight.setAddr(Byte.valueOf(deviceCabinetBox.getAddress_485()));

					openFireService.sendMessage(deviceController.getOpenfire_username(),
							JsonUtil.serialize(cabinetBoxGetWeight), UUID.randomUUID().toString(),
							new MessageListener() {

								@Override
								public String processAndGetReply(Message message) {
									System.out.println(message.getBody());
									return null;
								}

							});
				}
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/cabinetBoxSearch.xhtml")
	public String cabinetBoxSearch(String uuid) {
		DeviceCabinetBox deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class, uuid);
		if (null != deviceCabinetBox && deviceCabinetBox.getDeviceGateway().getUuid() != null) {
			DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class,
					deviceCabinetBox.getDeviceGateway().getUuid());
			if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
				DeviceController deviceController = daoService.getObject(DeviceController.class,
						deviceGateway.getDeviceController().getUuid());
				if (null != deviceController && deviceController.getOpenfire_username() != null) {
					CabinetBoxSearch cabinetBoxSearch = new CabinetBoxSearch();
					cabinetBoxSearch.setControllerIdentifiedNo(deviceController.getIdentified_no());
					cabinetBoxSearch.setGatewayIdentifiedNo(deviceGateway.getIdentified_no());
					cabinetBoxSearch.setAddr(Byte.valueOf(deviceCabinetBox.getAddress_485()));

					System.out.println("搜索命令");

					openFireService.sendMessage(deviceController.getOpenfire_username(),
							JsonUtil.serialize(cabinetBoxSearch), UUID.randomUUID().toString(), new MessageListener() {

								@Override
								public String processAndGetReply(Message message) {
									System.out.println(message.getBody());
									return null;
								}

							});
				}
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/cabinetBoxSigObjWeight.xhtml")
	public String cabinetBoxSigObjWeight(String uuid, Boolean state) {
		DeviceCabinetBox deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class, uuid);
		if (null != deviceCabinetBox && deviceCabinetBox.getDeviceGateway().getUuid() != null) {
			DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class,
					deviceCabinetBox.getDeviceGateway().getUuid());
			if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
				DeviceController deviceController = daoService.getObject(DeviceController.class,
						deviceGateway.getDeviceController().getUuid());
				if (null != deviceController && deviceController.getOpenfire_username() != null) {
					CabinetBoxSigObjWeight cabinetBoxSigObjWeight = new CabinetBoxSigObjWeight();
					cabinetBoxSigObjWeight.setGatewayIdentifiedNo(deviceGateway.getIdentified_no());
					cabinetBoxSigObjWeight.setAddr(Byte.valueOf(deviceCabinetBox.getAddress_485()));

					openFireService.sendMessage(deviceController.getOpenfire_username(),
							JsonUtil.serialize(cabinetBoxSigObjWeight), UUID.randomUUID().toString(),
							new MessageListener() {

								@Override
								public String processAndGetReply(Message message) {
									System.out.println(message.getBody());
									return null;
								}

							});
				}
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/cabinetBoxSigObjWeightErr.xhtml")
	public String cabinetBoxSigObjWeightErr(String uuid) {
		DeviceCabinetBox deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class, uuid);
		if (null != deviceCabinetBox && deviceCabinetBox.getDeviceGateway().getUuid() != null) {
			DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class,
					deviceCabinetBox.getDeviceGateway().getUuid());
			if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
				DeviceController deviceController = daoService.getObject(DeviceController.class,
						deviceGateway.getDeviceController().getUuid());
				if (null != deviceController && deviceController.getOpenfire_username() != null) {
					CabinetBoxSigObjWeightErr cabinetBoxSigObjWeightErr = new CabinetBoxSigObjWeightErr();
					cabinetBoxSigObjWeightErr.setGatewayIdentifiedNo(deviceGateway.getIdentified_no());
					cabinetBoxSigObjWeightErr.setAddr(Byte.valueOf(deviceCabinetBox.getAddress_485()));
					cabinetBoxSigObjWeightErr.setSig_weight_err(deviceCabinetBox.getDz_value_err().getBytes());

					openFireService.sendMessage(deviceController.getOpenfire_username(),
							JsonUtil.serialize(cabinetBoxSigObjWeightErr), UUID.randomUUID().toString(),
							new MessageListener() {

								@Override
								public String processAndGetReply(Message message) {
									System.out.println(message.getBody());
									return null;
								}

							});
				}
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@RequestMapping(value = "/manager/device/cabinetbox/getcache.xhtml")
	public String getCache(String uuid) {
		DeviceCabinetBox deviceCabinetBox = daoService.getObject(DeviceCabinetBox.class, uuid);
		if (null != deviceCabinetBox && deviceCabinetBox.getDeviceGateway().getUuid() != null) {
			DeviceGateway deviceGateway = daoService.getObject(DeviceGateway.class,
					deviceCabinetBox.getDeviceGateway().getUuid());
			if (null != deviceGateway && deviceGateway.getDeviceController().getUuid() != null) {
				DeviceController deviceController = daoService.getObject(DeviceController.class,
						deviceGateway.getDeviceController().getUuid());
				if (null != deviceController && deviceController.getOpenfire_username() != null) {
					String key = deviceController.getIdentified_no().concat("_")
							.concat(deviceGateway.getIdentified_no()).concat("_")
							.concat(deviceCabinetBox.getAddress_485());
					redisCacheService.get(redisCacheService.REGION_TWENTYMIN, key);
				}
			}
		}

		HttpServletRequest request = getRequest();
		request.setAttribute(FancyVelocityView.RENDER_JSON, "true");
		request.setAttribute(FancyVelocityView.DIRECT_OUTPUT,
				new JsonStrDirectOut(getResponse(), JsonUtil.serialize(new HashMap())));
		return "common/directOut.vm";
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub

	}
}
